<?php
namespace App\Http\Controllers\Api;
use App\Lib\Uploads\UploadHandler;
use App\Models\Posts\WxPostsVideo;
use App\Models\WxAttachment;
use App\Models\Circle\WxCircle;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\SiteUtils;
use App\Wen\Utils\StatisticUtils;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;

class AdminController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_dashboard_data(Request $request)
    {
        $uid = $request->uid;
        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000, [], '你还不是超级管理员啊');
        }
        global $__MINI_GLOBAL_PAYCODE_0__;
        // 在线人数
        $online_users_count = UserUtils::user_onlines();
        $user_total = StatisticUtils::total_user_count();
        $totay_payment = StatisticUtils::totay_payment_count();
        $mini_version = get_mini_version_code();
        $total_todo_arr = StatisticUtils::total_todo_count(true);
        $result = [
            'is_auth' => $__MINI_GLOBAL_PAYCODE_0__,
            'user_online' => $online_users_count,
            'user_total' => $user_total,
            'today_user_register' => StatisticUtils::today_user_register_count(),
            'totay_payment' => $totay_payment,
            'coins_total' => StatisticUtils::get_coins_total(),
            'blance_total' => StatisticUtils::get_blance_total(),
            'mini_version' => $mini_version,
            'total_todo' => array_sum($total_todo_arr),
            'post_todo' => $total_todo_arr[0],
            'comment_todo' => $total_todo_arr[1],
            'circle_todo' => $total_todo_arr[2],
            'withdrawl_todo' => $total_todo_arr[3],
            'temp_todo' => $total_todo_arr[4],
            'feedback_todo' => $total_todo_arr[5],
            'is_examine_mode' => is_mini_examine_mode() ? true : false,
            'is_auto_back_upgrade' => false,
            'monitor' => [
                'schedule' => Cache::has('schedule') ? 1 : 0,
                'queue' => Cache::get('queue:increment:times', 0) > 15 ? 0 : 1,
                'websocket' => GatewayUtils::uid2client_id($uid) ? 1 : 0
            ]
        ];
        return $this->success($result);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function circle_setting(Request $request){
        $uid = $request->uid;
        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000, [], '你还不是超级管理员啊');
        }
        global $__MINI_GLOBAL_PAYCODE_15__;
        if(!$__MINI_GLOBAL_PAYCODE_15__){
            return $this->fail(700000);
        }

        $circle_id = $request->circle_id;

        if(_empty_($circle_id)){
            return $this->fail(200001);
        }

        $selidx = $request->selidx;
        $selidx2 = $request->selidx2;
        $followPay = $request->followPay;
        $followPayType = $request->followPayType;
        $followPayDuration = $request->followPayDuration;
        $publishPay = $request->publishPay;
        $publishPayType = $request->publishPayType;
        $circle_user_paycontent_division = $request->circle_user_paycontent_division;
        $circle_user_division = $request->circle_user_division;


        $__circle_user_division = 0;
        $__circle_user_paycontent_division = 0;
        $__is_follow_authentication = 0;
        $__is_follow_vip = 0;
        $__is_follow_pay = 0;
        $__follow_pay_num = 0;
        $__follow_pay_credit = 0;
        $__follow_pay_duration = 0;
        $__is_follow_admin = 0;

        $__is_publish_follow = 0;
        $__is_publish_vip = 0;
        $__is_publish_pay = 0;
        $__is_publish_authentication = 0;
        $__is_publish_admin = 0;
        $__publish_pay_num = 0;
        $__publish_pay_credit = 0;


        if($circle_user_division >= 0 && $circle_user_division <= 100){
            $__circle_user_division = (int)$circle_user_division / 100;
        }else{
            return $this->fail(200001, [], '['.env('circle_user_call', '圈主').'其他分成]输入错误！');
        }

        if($circle_user_paycontent_division >= 0 && $circle_user_paycontent_division <= 100){
            $__circle_user_paycontent_division = (int)$circle_user_paycontent_division / 100;
        }else{
            return $this->fail(200001, [], '['.env('circle_user_call', '圈主').'付费内容分成]输入错误！');
        }

        if(_array_key($selidx, 0, '') && _array_key($selidx, 0, '') == '认证用户'){
            $__is_follow_authentication = 1;
        }

        if(_array_key($selidx, 1, '') && _array_key($selidx, 1, '') == '会员'){
            $__is_follow_vip = 1;
        }

        if(_array_key($selidx, 2, '') && _array_key($selidx, 2, '') == '管理员'){
            $__is_follow_admin = 1;
        }

        if(_array_key($selidx, 3, '') && _array_key($selidx, 3, '') == '付费'){
            $__follow_pay_duration = (int)$followPayDuration;
            $__follow_pay_credit = $followPayType ? 1 : 0;

            if($__follow_pay_credit == 0){
                $__follow_pay_num = (int)$followPay;
            }else{
                $__follow_pay_num = round($followPay, 2);
            }

            if($__follow_pay_num <= 0 || $__follow_pay_duration <= 0){
                return $this->fail(200001, [], '开启付费关注时，付费金额及时长必须大于0');
            }
            $__is_follow_pay = 1;
        }

        if(_array_key($selidx2, 0, '') && _array_key($selidx2, 0, '') == '已关注用户'){
            $__is_publish_follow = 1;
        }

        if(_array_key($selidx2, 1, '') && _array_key($selidx2, 1, '') == '认证用户'){
            $__is_publish_authentication = 1;
        }

        if(_array_key($selidx2, 2, '') && _array_key($selidx2, 2, '') == '会员'){
            $__is_publish_vip = 1;
        }

        if(_array_key($selidx2, 3, '') && _array_key($selidx2, 3, '') == '管理员'){
            $__is_publish_admin = 1;
        }

        if(_array_key($selidx2, 4, '') && _array_key($selidx2, 4, '') == '付费按次发布'){
            if($publishPay <= 0){
                return $this->fail(200001, [], '开启付费按次发布时，付费数额必须大于0！');
            }
            $__is_publish_pay = 1;
            $__publish_pay_credit = $publishPayType ? 1 : 0;
            if($__publish_pay_credit == 0){
                $__publish_pay_num = (int)$publishPay;
            }else{
                $__publish_pay_num = round($publishPay, 2);
            }

        }

        $updates = [];
        if($__circle_user_division > 0){
            $updates['circle_user_division'] = $__circle_user_division;
        }else{
            $updates['circle_user_division'] = 0;
        }
        if($__circle_user_paycontent_division > 0){
            $updates['circle_user_paycontent_division'] = $__circle_user_paycontent_division;
        }else{
            $updates['circle_user_paycontent_division'] = 0;
        }

        if($__is_follow_authentication == 1){
            $updates['is_follow_authentication'] = 1;
        }else{
            $updates['is_follow_authentication'] = 0;
        }

        if($__is_follow_vip == 1){
            $updates['is_follow_vip'] = 1;
        }else{
            $updates['is_follow_vip'] = 0;
        }

        if($__is_follow_admin == 1){
            $updates['is_follow_admin'] = 1;
        }else{
            $updates['is_follow_admin'] = 0;
        }

        if($__is_follow_pay == 1 && $__follow_pay_num > 0 && $__follow_pay_duration > 0){
            $updates['is_follow_pay'] = 1;
            $updates['follow_pay_num'] = $__follow_pay_num;
            $updates['follow_pay_credit'] = $__follow_pay_credit == 1 ? 1 : 0;
            $updates['follow_pay_duration'] = $__follow_pay_duration;
        }else{
            $updates['is_follow_pay'] = 0;
            $updates['follow_pay_num'] = 0;
            $updates['follow_pay_credit'] = 0;
            $updates['follow_pay_duration'] = 0;
        }

        if($__is_publish_follow == 1){
            $updates['is_publish_follow'] = 1;
        }else{
            $updates['is_publish_follow'] = 0;
        }

        if($__is_publish_vip == 1){
            $updates['is_publish_vip'] = 1;
        }else{
            $updates['is_publish_vip'] = 0;
        }

        if($__is_publish_authentication == 1){
            $updates['is_publish_authentication'] = 1;
        }else{
            $updates['is_publish_authentication'] = 0;
        }

        if($__is_publish_pay == 1 && $__publish_pay_num > 0){
            $updates['is_publish_pay'] = 1;
            $updates['publish_pay_num'] = $__publish_pay_num;
            $updates['publish_pay_credit'] = $__publish_pay_credit == 1 ? 1 : 0;
        }else{
            $updates['is_publish_pay'] = 0;
            $updates['publish_pay_num'] = 0;
            $updates['publish_pay_credit'] = 0;
        }

        if($__is_publish_admin == 1){
            $updates['is_publish_admin'] = 1;
        }else{
            $updates['is_publish_admin'] = 0;
        }

        $__global_config_version__ = Settings::get('__global_config_version__', 1) + 1;
        Settings::set('__global_config_version__', $__global_config_version__);
        GatewayUtils::success('all', 13, [ 'version' => $__global_config_version__, 'file' => basename(__FILE__) ]);

        return $this->success(WxCircle::where('id', $circle_id)->update($updates));
    }

    /**
     * 管理员删除附件
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete_attachment(Request $request){
        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }
        $uid = $request->uid;
        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000, [], '你还不是超级管理员啊');
        }
        $id = $request->id;
        if(_empty_($id)){
            return $this->fail(200001);
        }
        $obj = WxAttachment::find($id);
        if(_empty_($obj)){
            return $this->fail(200003);
        }
        if($obj->state == 2){
            return $this->fail(200004, [], '该附件已经被清理过');
        }
        if(UploadHandler::del($obj)){
            return $this->success();
        }else{
            return $this->fail(200006, [], '清理失败');
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function imgs(Request $request){
        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }
        $uid = $request->uid;
        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000, [], '你还不是超级管理员啊');
        }
        $data = WxAttachment::where('user_id', '>', 0)->where('state', '<>', 2)->orderBy('created_at', 'desc')->simplePaginate(28);
        if($data){
            $data->map(function ($v){
                if(strpos($v->path, '.') === false){
                    $v->type = '';
                }else{

                }
                if(StrUtils::endsWith($v->path, '.mp4')){
                    $v->url =  $v->domain . '/' . $v->path;
                    $v->file_type = 'video';
                }else if(StrUtils::endsWith($v->path, ['.jpg', '.png', 'jpeg', '.webp', '.gif'])){
                    $v->file_type = 'image';
                    $v->url = Utils::imgWithStyle(($v->domain . '/' . $v->path), 2);
                }else{
                    $v->file_type = 'other';
                }

                $allowable = [
                    [
                        'text' => '附件ID',
                        'type' => 'copy',
                        'id' => $v->id,
                        'raw' => $v->id,
                        'icon' => 'mini-icon mini-fuzhi'
                    ],
                    [
                        'text' => '删除',
                        'type' => 'delete',
                        'id' => $v->id,
                        'icon' => 'mini-icon2 mini-shanchu'
                    ]
                ];
                $v->allowable = $allowable;
                return $v;
            });
        }
        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setting(Request $request){
        $uid = $request->uid;
        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000, [], '你还不是超级管理员啊');
        }

        $key = $request->key;
        $value = $request->value;


        if(_empty_($key)){
            return $this->fail(200001);
        }


        if($key == 'is_examine_mode'){
            // 一键审核模式
            if($value == true){
                is_mini_examine_mode(2);
                Artisan::queue('chmod:run');
            }else{
                is_mini_examine_mode(3);
            }
        }else if($key == 'is_auto_back_upgrade'){

        }

        SiteUtils::forget_config_data();


        $__global_config_version__ = Settings::get('__global_config_version__', 1) + 1;
        Settings::set('__global_config_version__', $__global_config_version__);
        GatewayUtils::success('all', 13, [ 'version' => $__global_config_version__, 'file' => basename(__FILE__) ]);
        return $this->success();
    }
}
